import pkg from '/package.json'
import manifest from '@/manifest.json'

interface GlobalSetting {
  /* 开发环境 */
  readonly isDev: boolean
  /* 是否开发环境api */
  readonly isDevServer: boolean
  /* 请求的apiUrl */
  readonly apiUrl: string
  readonly name: string
  readonly version: string
  /* 当前小程序AppId */
  readonly wxAppId: string
  /* 默认的appCode */
  readonly appCode: string
  /* 当前应用的租户 */
  readonly tenantId: string
  /* 是否为定制租户应用 */
  readonly isCustom: boolean
  /* 当前小程序是否进行登陆鉴权 */
  readonly checkAuth: boolean
  /* 是否开放注册入口 */
  readonly openRegister: boolean
  /* 服务协议、隐私政策链接网址 */
  readonly privacyUrl: string[]
  /* 模板消息订阅ids(写成json字符串形式) */
  readonly tmpIds: string[]
}

export function useGlobalSetting(): GlobalSetting {
  const envConfig = getEnvConfig()
  const { version } = pkg

  return {
    isDev: envConfig.NODE_ENV === 'development',
    name: manifest.name,
    isDevServer: envConfig.VUE_APP_API_URL.includes('/v2_java') ?? false,
    apiUrl: envConfig.VUE_APP_API_URL,
    version,
    wxAppId: manifest['mp-weixin'].appid,
    appCode: envConfig.VUE_APP_APP_CODE,
    tenantId: envConfig.VUE_APP_TENANTID,
    isCustom: envConfig.VUE_APP_IS_CUSTOM,
    checkAuth: envConfig.VUE_APP_NEED_LOGIN,
    openRegister: envConfig.VUE_APP_OPEN_REGISTER,
    privacyUrl: envConfig.VUE_APP_PRIVACY_URI,
    tmpIds: envConfig.VUE_APP_APP_TMPIDS
  }
}

function getEnvConfig() {
  const {
    NODE_ENV = 'development',
    VUE_APP_APP_CODE = '',
    VUE_APP_API_URL = '',
    VUE_APP_TENANTID = '99',
    VUE_APP_IS_CUSTOM = false,
    VUE_APP_NEED_LOGIN = false,
    VUE_APP_OPEN_REGISTER = false,
    VUE_APP_PRIVACY_URI = '',
    VUE_APP_APP_TMPIDS = ''
  } = process.env

  return {
    NODE_ENV,
    VUE_APP_APP_CODE,
    VUE_APP_API_URL,
    VUE_APP_TENANTID,
    VUE_APP_IS_CUSTOM: VUE_APP_IS_CUSTOM === 'true',
    VUE_APP_NEED_LOGIN: VUE_APP_NEED_LOGIN === 'true',
    VUE_APP_OPEN_REGISTER: VUE_APP_OPEN_REGISTER === 'true',
    VUE_APP_PRIVACY_URI: VUE_APP_PRIVACY_URI.split(','),
    VUE_APP_APP_TMPIDS: VUE_APP_APP_TMPIDS.split(',')
  }
}
